import React, { useState, useEffect, useMemo } from 'react'
import { Input, AutoComplete, Tag, Divider, Typography, Space } from 'antd'
import { SearchOutlined, HistoryOutlined, FireOutlined } from '@ant-design/icons'
import { debounce } from 'lodash'

const { Text } = Typography

const SmartSearch = ({
  placeholder = "智能搜索...",
  onSearch,
  searchHistory = [],
  hotSearches = [],
  suggestions = [],
  loading = false,
  style,
}) => {
  const [searchValue, setSearchValue] = useState('')
  const [options, setOptions] = useState([])
  const [showDropdown, setShowDropdown] = useState(false)

  // 防抖搜索
  const debouncedSearch = useMemo(
    () => debounce((value) => {
      if (onSearch) {
        onSearch(value)
      }
    }, 300),
    [onSearch]
  )

  useEffect(() => {
    if (searchValue.trim()) {
      debouncedSearch(searchValue)
    }
  }, [searchValue, debouncedSearch])

  // 生成搜索选项
  useEffect(() => {
    const newOptions = []

    if (searchValue.trim()) {
      // 搜索建议
      if (suggestions.length > 0) {
        newOptions.push({
          label: (
            <div>
              <Text strong>搜索建议</Text>
              <Divider style={{ margin: '8px 0' }} />
            </div>
          ),
          options: suggestions.map((item, index) => ({
            value: item.text,
            label: (
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>{item.text}</span>
                <Tag color="blue">{item.type}</Tag>
              </div>
            ),
          })),
        })
      }
    } else {
      // 搜索历史
      if (searchHistory.length > 0) {
        newOptions.push({
          label: (
            <div>
              <HistoryOutlined style={{ marginRight: 8 }} />
              <Text strong>搜索历史</Text>
              <Divider style={{ margin: '8px 0' }} />
            </div>
          ),
          options: searchHistory.slice(0, 5).map((item, index) => ({
            value: item,
            label: (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <HistoryOutlined style={{ marginRight: 8, color: '#999' }} />
                <span>{item}</span>
              </div>
            ),
          })),
        })
      }

      // 热门搜索
      if (hotSearches.length > 0) {
        newOptions.push({
          label: (
            <div>
              <FireOutlined style={{ marginRight: 8, color: '#ff4d4f' }} />
              <Text strong>热门搜索</Text>
              <Divider style={{ margin: '8px 0' }} />
            </div>
          ),
          options: hotSearches.slice(0, 5).map((item, index) => ({
            value: item.text,
            label: (
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>{item.text}</span>
                <Tag color="red">{item.count}</Tag>
              </div>
            ),
          })),
        })
      }
    }

    setOptions(newOptions)
  }, [searchValue, suggestions, searchHistory, hotSearches])

  const handleSearch = (value) => {
    setSearchValue(value)
    setShowDropdown(false)
    if (onSearch) {
      onSearch(value)
    }
  }

  const handleSelect = (value) => {
    setSearchValue(value)
    setShowDropdown(false)
    if (onSearch) {
      onSearch(value)
    }
  }

  return (
    <AutoComplete
      style={{ width: '100%', ...style }}
      options={options}
      value={searchValue}
      onChange={setSearchValue}
      onSelect={handleSelect}
      onFocus={() => setShowDropdown(true)}
      onBlur={() => setTimeout(() => setShowDropdown(false), 200)}
      open={showDropdown}
      dropdownMatchSelectWidth={false}
      dropdownStyle={{ minWidth: 300 }}
    >
      <Input.Search
        placeholder={placeholder}
        enterButton={<SearchOutlined />}
        loading={loading}
        onSearch={handleSearch}
        allowClear
      />
    </AutoComplete>
  )
}

export default SmartSearch

// 全局搜索 Hook
export const useGlobalSearch = () => {
  const [searchResults, setSearchResults] = useState([])
  const [loading, setLoading] = useState(false)
  const [searchHistory, setSearchHistory] = useState([])

  const search = async (query) => {
    if (!query.trim()) {
      setSearchResults([])
      return
    }

    setLoading(true)
    try {
      // 这里应该调用实际的搜索 API
      const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`)
      const data = await response.json()
      
      setSearchResults(data.results || [])
      
      // 更新搜索历史
      setSearchHistory(prev => {
        const newHistory = [query, ...prev.filter(item => item !== query)]
        return newHistory.slice(0, 10) // 只保留最近10条
      })
    } catch (error) {
      console.error('搜索失败:', error)
      setSearchResults([])
    } finally {
      setLoading(false)
    }
  }

  return {
    searchResults,
    loading,
    searchHistory,
    search,
  }
}